<?php

/*
 * @Item Model
 * @verion 1.0
 * @author Roshan
 */

class Application extends base {
	
	protected $_view;
	
	public function __construct() {
		// $this->setView();
	}
	
	public function run($view = '') {
		// GET ALL THE CATEGOREIS FOR SEARCH SELECT
		view::newInstance ()->_exportVariableToView ( 'main_categories', Model_Mapper_Categories::newInstance ()->tree () );
		switch (params::getParam ( 'action' )) {
			
			case 'new' :
				
				// get top level categories
				$categories = Model_Mapper_Categories::newInstance ()->getTopCategories ();
				//$tree=Model_Mapper_Categories::newInstance()->tree();
				//print_r($tree);
				//view::newInstance ()->_exportVariableToView ( 'tree', $tree );
				view::newInstance ()->_exportVariableToView ( 'top_categories', $categories );
				$location = Model_Mapper_Locations::newInstance ()->getTopLocations ( true );
				//$tree=Model_Mapper_Locations::newInstance()->tree();
				//view::newInstance ()->_exportVariableToView ( 'location_tree', $tree );
				//print_r($tree);
				view::newInstance ()->_exportVariableToView ( 'top_locations', $location );
				//print_r($location);
				

				Session::newInstance ()->_clearVariables ();
				unset ( $categories );
				unset ( $location );
				$this->setView ( 'new-item-user-logged-in.phtml' );
				
				if (isset ( $_GET ['category_id'] ) && isset ( $_GET ['location_id'] )) {
					
					$this->setView ( 'new-item.phtml' );
				} else {
					
					$this->setView ( 'new-item-step1.phtml' );
				}
				
				$this->dispatch ();
				
				break;
			
			case 'post' :
				
				$error = false;
				$error_message = array ();
				
				// FIRST CHECK IF EMAIL IS ALREADY USED. if email exits ask user to login
				$args = array ();
				$args ['name'] = '';
				$args ['description'] = '';
				$args ['price'] = '';
				$args ['urgent'] = 0;
				$args ['use_in_map'] = 0;
				$args ['local_area'] = '';
				$args ['postcode'] = '';
				$args ['youtube_url'] = '';
				$args ['category_id'] = '';
				$args ['location_id'] = '';
				$args ['email'] = '';
				
				foreach ( $_POST as $key => $value ) {
					if (array_key_exists ( $key, $args )) {
						$args [$key] = $value;
					}
				}
				
				if (isset ( $_POST ['urgent'] )) {
					$args ['urgent'] = 1;
				}
				
				if (isset ( $_POST ['use_in_map'] )) {
					$args ['use_in_map'] = 1;
				}
				
				// set defaults
				$args ['publish_date'] = date ( 'Y-m-d H:i:s' );
				
				// NEED TO WORK ON EXPIRES LATER
				//$args ['expires'] = date ( 'Y-m-d H:i:s', time () + (15 * 60) ); // for about 15 minutes;
				

				if (! Helper_Item::newInstance ()->validate_name ( $args ['name'] )) {
					$error = true;
					$error_message [] = 'The Title for ad is either too short.';
				} else {
					$args ['name'] = Helper_Item::newInstance ()->sanitize_name ( $args ['name'] );
				}
				
				if ($args ['category_id'] == '') {
					$error = true;
					$error_message [] = 'Category is not selected.';
				}
				
				if ($args ['location_id'] == '') {
					$error = true;
					$error_message [] = 'Location is not selected.';
				}
				
				if (! Helper_Item::newInstance ()->validate_description ( $args ['description'] )) {
					$error = true;
					$error_message [] = 'Ad Description is too short.';
				} else {
					$args ['description'] = Helper_Item::newInstance ()->sanitize_description ( $args ['description'] );
				}
				
				if ($args ['price'] == '') {
					$error = true;
					$error_message [] = 'Price is not set.';
				}
				
				if (! Helper_Item::newInstance ()->validate_price ( $args ['price'] )) {
					$error = true;
					$error_message [] = 'Invalid Price is given.';
				} else {
					$args ['price'] = Helper_Item::newInstance ()->sanitize_price ( $args ['price'] );
				}
				
				if ($args ['postcode'] == '') {
					$error = true;
					$error_message [] = 'Postcode is not given';
				}
				
				Session::newInstance ()->_setForm ( 'new_post', $args );
				Session::newInstance ()->_setMessage ( 'post_error', $error_message, 'error' );
				
				$args ['user_id'] = 0;
				if (! user_logged_in ()) {
					if (filter_var ( $_POST ['email'], FILTER_VALIDATE_EMAIL )) {
						$error = false;
					} else {
						$error = true;
						$error_message [] = 'Invalid Email used. Please use proper email: e.g. example@domain.com';
					}
				}
				Session::newInstance ()->_setMessage ( 'post_error', $error_message, 'error' );
				// CHECK IF THERE IS ANY ERROR
				if (! $error) {
					if (user_logged_in ()) {
						$user = Session::newInstance ()->_get ( 'current_user' );
						$args ['user_id'] = $user->getUser_id ();
						unset ( $user ); // unset to save memory
					

					} else if (isset ( $_POST ['register'] ) && $_POST ['register'] == 'yes') {
						// register user	
						$usr = array ('email' => $_POST ['email'] );
						$usr ['password'] = sha1 ( trim ( $_POST ['password'] ) );
						$user = new Model_User ( $usr );
						$user->save ();
						$user->sendActivationEmail ();
						Model_Mapper_User::newInstance ()->checkLogin ( $_POST ['email'], $_POST ['password'] );
					
					} else {
						Model_Mapper_User::newInstance ()->checkLogin ( $_POST ['email'], $_POST ['password'] );
					
					}
					
					if (user_logged_in ()) {
						// save the ad now
						$user = Session::newInstance ()->_get ( 'current_user' );
						$args ['user_id'] = $user->getUser_id ();
					} else {
						$error = true;
						$error_message [] = 'Invalid username or password. Please check username and password.';
					}
				
				} else {
					$form = Session::newInstance ()->_getForm ( 'new_post' );
					View::newInstance ()->_exportVariableToView ( 'form', $form );
				}
				
				if (! $error) {
					
					$item = new Model_Items ( $args );
					$item->save ();
					$item->sendActivationEmail ();
					$cat = Model_Mapper_Categories::newInstance ()->getByID ( $args ['category_id'] );
					$c = $cat->getRoot ();
					$slug = $c->getSlug ();
					// NOW INCLUDE AND  CALL CATEGORY FIELD SAVE OPTIONS
					if (file_exists ( plugin_path () . $slug . DS . 'item_post.php' )) {
						include plugin_path () . $slug . DS . 'item_post.php';
					}
					Session::newInstance ()->_clearVariables ();
					
					//NOW SAVE IMAGE IF EXISTS
					//
					$max_height = 1024;
					$max_width = 1024;
					Params::_view ();
					if (Params::getFiles ( 'image' )) { // image exists
						$img = Params::getFiles ( 'image' );
						$imgsizer = new Image_Resize ();
						$imgsizer->load ( $img ['tmp_name'] );
						$ext = '.jpg';
						if ($imgsizer->image_type == IMAGETYPE_JPEG) {
							$ext = '.jpg';
						} else if ($imgsizer->image_type == IMAGETYPE_GIF) {
							$ext = '.gif';
						} else {
							$ext = '.png';
						}
						$image_name = $item->getItem_id () . $item->getSlug () . $ext;
						$path = content_path () . 'item_images' . DS . $image_name;
						
						if ($imgsizer->getHeight () > $imgsizer->getWidth ()) {
							$imgsizer->resizeToWidth ( $max_width );
						} else {
							$imgsizer->resizeToHeight ( $max_height );
						}
						$imgsizer->save ( $path );
						$resource = new Model_ItemResource ();
						$resource->setItem_id ( $item->getItem_id () );
						$resource->setName ( $image_name );
						$resource->setType ( 'primary' );
						$resource->save ();
					}
					
					redirect ( 'user/dashboard/' );
				} else {
					Session::newInstance ()->_setMessage ( 'post_error', $error_message, 'error' );
					redirect ( 'item/new/' );
				}
				break;
			
			case 'activate' :
				$secret = Params::getParam ( 'secret' );
				if (! $secret == '') {
					$item = Model_Mapper_Items::newInstance ()->getBySecret ( $secret );
					if ($item) {
						$item->activate ();
						redirect ( $item->getURI () );
					}
				}
				break;
			
			case 'edit' :
				break;
			
			case 'all' :
				$args = array ();
				$args [] = 'item-one';
				$args [] = 'item-two';
				
				//print_r ( item::newInstance ()->findBySlug ( $args ) );
				$this->setView ( 'item_all.phtml' );
				
				break;
			case 'index' :
				$item = Model_Mapper_Items::newInstance ()->getBySlug ( Params::getParam ( 'slug' ) );
				$item->increaseView ();
				$cat = $item->getCategory ();
				$breadcrumb = $cat->toRoot ();
				Breadcrumb::newInstance ()->add ( $item->getName (), $item->getURI () );
				foreach ( $breadcrumb as $cat_item ) {
					breadcrumb::newInstance ()->add ( $cat_item->getName (), $cat_item->getURI () );
				}
				
				view::newInstance ()->_exportVariableToView ( 'item', $item );
				$this->setView ( 'item_detail.phtml' );
				$this->dispatch ();
				break;
		}
	
	}

}